package com.wanke.publish;

import com.wanke.constant.EventConstant;
import com.wanke.constant.ProtocolConstants;
import com.wanke.domain.po.Measurements;
import com.wanke.service.MeasurementService;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.MessageConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.wanke.subscribe.MqttMeasuremenSubscribetRecevice;

/**
 * 云端量测上传程序
 * @author diaoshili
 * @date 2020-01-19
 */
public abstract class RemoteMeasurePublish extends AbstractVerticle implements Handler<Measurements> {

    private static final Logger logger = LoggerFactory.getLogger(MqttMeasuremenSubscribetRecevice.class);

    /**
     * 启动数据补传和心跳监测，以及订阅eventBus量测上传事件
     * @param startPromise
     * @throws Exception
     */
    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        heartBeatStart();
        resendStart();
        MessageConsumer<Measurements> meassageHandler = vertx.eventBus().localConsumer(EventConstant.MEAS_PUBLISH.name());
        meassageHandler.handler(a-> {
            logger.error(this.getProtocol() + "准备发送消息");
            this.handle(a.body());
        });
    }

    /**
     * 收到量测后去处理,如果发送错误就调用存储类进行存储
     * @param value 量测结果集
     */
    @Override
    public void handle(Measurements value) {
        MeasurementService measurementService = this.getMeasurementService();
        measurementService.insertBackMeasurement(value.getMeasurementList());
        if (!isConnect()) {
            logger.error("{}协议当前是断开",this.getProtocol().name());
            onTempStore(value);
            return;
        }
        toSend(value);
    }

    /**
     * 存储当前量测
     */
    public  abstract void onTempStore(Measurements measurements);


    /**
     * 获得网络状态 true 为正常连接, false 为断开
     * @return
     */
    public abstract  boolean isConnect();

    /**
     * 发送量测
     * @return
     */
    public  abstract  void toSend(Measurements measurements);


    /**
     * 是需要发送量测的
     * @return
     */
    public  abstract  void resendStart();


    /**
     * 获得更新网络状态
     * @return
     */
    public abstract  void heartBeatStart();


    /**
     * 获得协议名称
     * @return
     */
    public abstract ProtocolConstants getProtocol();

    /**
     * 获得量测数据仓库
     */
    public abstract MeasurementService getMeasurementService();
}
